import axios from "axios";
import {
  Toast
} from "./utils";
import {
  getToken,
  removeToken
} from "./auth";
import {
  router
} from "@/router";
//1. 创建axios对象
const service = axios.create({
  baseURL: "/api",
  timeout: 10000,
});

//2. 请求拦截器
service.interceptors.request.use(
  (config) => {
    let token = getToken();
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

//3. 响应拦截器
service.interceptors.response.use(
  (response) => {
    //判断code码
    // console.log(response);
    if (response.status == 200) {
      return {
        data: response.data.data,
        status: response.status,
      };
    } else {
      return response.data;
    }
  },
  (error) => {
    // console.log("拦截到错误", error);
    if (error.response.data.errorCode === 20000) {
      Toast(error.response.data.msg || "网络错误", "error");
      removeToken();
      router.push("/login");
    }
    if (error.response.data.errorCode === 40000) {
      Toast('当前是Vue3实战商城后台管理系统的演示站点，仅供演示，禁止操作');

    }
    // Promise.reject(error);
    return error;
  }
);

export default service;